<?php
header("Content-Type: text/html; charset=iso-8859-1");

//
//  include.php
//  vbcll2
//
//  Created by Robin on 2007-02-20.
//  Copyright (c) 2007 __MyCompanyName__. All rights reserved.
//
ini_set("display_errors","off");

if(!defined("TITRE_TWEET")) define("TITRE_TWEET","La semaine des tweets");
if(!isset($_SESSION)) session_start();


$jours = array("lu" => "lundi",
				"ma" => "mardi",
				"me" => "mercredi",
				"je" => "jeudi",
				"ve" => "vendredi",
				"sa" => "samedi",
				"di" => "dimanche");
$no_jours = array("di","lu","ma","me","je","ve","sa");
$days = array("Mon" => "lu",
			   "Tue" => "ma",
				"Wed" => "me",
				"Thu" => "je",
				"Fri" => "ve",
				"Sat" => "sa",
				"Son" => "di");


###### Classes ############

if(is_dir('include')){
	if ($handle = opendir('include')) {
	    while (false !== ($file = readdir($handle))) {
	        if(strstr($file,"inc") !== false && substr($file,0,1) !== '.') include("include/".$file);
	    }
	    closedir($handle);
	}
}

########################################
#Fonction redirect
#
if(!isset($FichierFonctions))
{
	$FichierFonctions = 1;

	function unregister_GLOBALS()
	{
	    if (!ini_get('register_globals')) {
	        return;
	    }

	    // Vous pouvez vouloir modifier cela pour avoir une erreur plus jolie
	    if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) {
	    die('Tentative d\'effacement des GLOBALS détectée');
	    }

	    // Les variables à ne jamais effacer
	    $noUnset = array('GLOBALS',  '_GET',
	    '_POST',    '_COOKIE',
	    '_REQUEST', '_SERVER',
	    '_ENV',     '_FILES');

	    $input = array_merge($_GET,    $_POST,
	    $_COOKIE, $_SERVER,
	    $_ENV,    $_FILES,
	    isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());

	    foreach ($input as $k => $v) {
	        if (!in_array($k, $noUnset) && isset($GLOBALS[$k])) {
	            unset($GLOBALS[$k]);
	        }
	    }
	}


  	function redirect($filename) {
        if (!headers_sent())
            header('Location: '.$filename);
        else {
            echo '<script type="text/javascript">';
            echo 'window.location.href="'.$filename.'";';
            echo '</script>';
            echo '<noscript>';
            echo '<meta http-equiv="refresh" content="0;url='.$filename.'" />';
            echo '</noscript>';
        }
    }

	###### Check_cookie

	function check_cookie(){
		$VBCLL = (!empty($_COOKIE['VBCLL2'])) ? $_COOKIE["VBCLL2"] : "";
		if($VBCLL){
			$cookie = explode(':',$VBCLL);
			if($membre = new membre($cookie[0])){
				if($cookie[1] == $cookie[0]*strlen($membre->nom) + strlen($membre->prenom)){
					if($membre->valide && !$membre->fictif) return $membre->id;
					else return 0;
				}
				else return 0;
			}
			else return 0;
		}
	}

	function check_cookie_email(){
		$VBCLL = (!empty($_COOKIE['VBCLL_EMAIL'])) ? $_COOKIE["VBCLL_EMAIL"] : "";
		if($VBCLL){
			return ($VBCLL=="EMAILOK") ? 1 : 0;
		}
		else return 0;
	}


	#### lien

	function lien($link,$text){
		$popup = "";
		if(func_num_args() > 2){
			if(func_get_arg(2) == 'popup'){
				$popup = "target = '_blank'";
			}
		}
		return "<a href = '$link' $popup>$text</a>";
	}

	function format_resultat($resultat,$local,$visiteur){
		$tab = explode("-",$resultat);
		if(count($tab) == 2){
			$class = ((strstr($local,"LUTRY") !== FALSE && $tab[0] > $tab[1]) || (strstr($visiteur,"LUTRY") !== FALSE && $tab[0] < $tab[1])) ? "gagne" : "perdu";
			return "<span class = '$class'>$resultat</span>";
		}
		else return "";
	}



	#### format_date
function format_heure($heure){
	if(strpos($heure,":") !== FALSE){
		$tab = explode(":",$heure);
		return $tab[0]."h".$tab[1];
	}
}

function format_tel($tel){
	return chunk_split(substr(ereg_replace("[^0-9]","",$tel),0,6),3)." ".chunk_split(substr(ereg_replace("[^0-9]","",$tel),6),2);
}

function format_date ($date, $format = "",$anniv = ""){
	$heure = "";
	if(strpos($date,":")){
		$date = substr($date,0,10);
	}
	$old_date = $date;
	if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
	   $year = ($anniv) ? date('Y') : $regs[1];
		$date =  "$regs[3].$regs[2].$year";
	}
	elseif(strlen($date) == 14){
		$date_ini = $date;
		$date = substr($date,6,2).".".(substr($date,4,2)).".".(substr($date,0,4)) ;
		$heure = " ".(substr($date_ini,8,2)).":".(substr($date_ini,10,2));
	}
	if(strpos($date,'.')){
		$demain = date('d.m.Y',mktime (0,0,0,date("m")  ,date("d")+1,date("Y")));
		$hier = date('d.m.Y',mktime (0,0,0,date("m")  ,date("d")-1,date("Y")));
		$demain1 = date('d.m.y',mktime (0,0,0,date("m")  ,date("d")+1,date("y")));
		$hier1 = date('d.m.y',mktime (0,0,0,date("m")  ,date("d")-1,date("y")));
		if($date==date('d.m.Y') || $date == date('d.m.y')){
		      $resultat = "<span class = 'highlight'>aujourd'hui</span>";
		}
		elseif($date==$demain || $date == $demain1){
		      $resultat = "demain";
		}
		elseif($date==$hier || $date == $hier1){
		      $resultat = "<span class = 'highlight'>hier</span>";
		}
		else $resultat = ($format) ? date("$format",safestrtotime($old_date)) : $date.$heure;
	}
	else{
		$demain = date('d M',mktime (0,0,0,date("m")  ,date("d")+1,date("Y")));
		$hier = date('d M',mktime (0,0,0,date("m")  ,date("d")-1,date("Y")));
		if($date==date('d M')){
		      $resultat = "<span class = 'highlight'>aujourd'hui</span>";
		}
		elseif($date==$demain){
		      $resultat = "demain";
		}
		elseif($date==$hier){
		      $resultat = "<span class = 'highlight'>hier</span>";
		}
		else $resultat = ($format) ? date("$format",safestrtotime($old_date)) : $date;
	}
	return($resultat);
}


#### Liste tables #######
function liste($table,$field='nom',$order= 'id'){
	$result = array();
	$q = "select id, $field from $table order by $order";
	$r = ExecRequete($q);
	while($s = LigneSuivante($r)){
		$result["$s->id"] = $s->$field;
	}
	return $result;
}

######### Stats ###########



############## Entete ######################

	function entete($title = '',$script = '', $onload = '',$admin=0){
		$page_title = 'LUTRY-LAVAUX';
		if($id = check_cookie()){
			$membre = new membre($id);
			$bienvenue = ($membre) ? "<a href = 'membre.php?id=$id&amp;action=complet'>$membre->prenom</a>" : "invit&eacute;";
		}
		else $bienvenue = 'invit&eacute;';
		$search_form = "Recherche:&nbsp;<input type = 'text' id = 'search_term' name = 'search_term'  onkeyup = \"	if(window.mytimeout) window.clearTimeout(window.mytimeout);	window.mytimeout = window.setTimeout(function(){
if(this.value) search(this.value,$admin);},500)\" />";
		$search_form .= "<span id='indicator_membre' style='display: none'><img src='images/spinner.gif' alt='recherche...' /></span>";
		$search_form .= "<input type = 'hidden' name = 'membre_id' id = 'membre_id' value = '' />";
		echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
			"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
		echo "<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='fr' lang='fr'>\n";
		echo "<head>\n";
		echo '<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />'."\n";
		$nb_equipes = count(liste('equipes'));
		echo "<meta name = 'description' content = 'Le Volley-Ball Club Lutry-Lavaux est form&eacute; de $nb_equipes masculines et f&eacute;minines. Le site pr&eacute;sente le club &agrave; travers ses actualit&eacute;s, les calendriers et r&eacute;sultats et son historique.' />";
		// echo '<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript" charset="utf-8"></script>'."\n";
		// echo '<script src="https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js" type="text/javascript" charset="utf-8"></script>'."\n";
		echo '<script src="javascripts/scriptaculous_bundle_min.js" type="text/javascript"></script>'."\n";
		echo '<script src="javascripts/vbcll.js" type="text/javascript" charset="iso-8859-1"></script>'."\n";
		// galerie highslide //

		if(basename($_SERVER['PHP_SELF']) == 'photos.php'){
			echo '<script src="javascripts/highslide-with-gallery.js" type="text/javascript" charset="iso-8859-1"></script>'."\n";
			echo '<script src="javascripts/highslide.config.js" type="text/javascript" charset="iso-8859-1"></script>'."\n";
			echo '<link rel="stylesheet" type="text/css" href="styles/highslide.css" />'."\n";
			echo '<!--[if lt IE 7]>'."\n";
			echo '<link rel="stylesheet" type="text/css" href="styles/highslide-ie6.css" />'."\n";
			echo '<![endif]-->'."\n";
		}

		// echo '<script src = "javascripts/tiny_mce/tiny_mce.js" type = "text/javascript"></script>'."\n";
		// echo '<script src = "javascripts/tiny_mce/tiny_mce.js" type = "text/javascript"></script>'."\n";
		echo '<script type="text/javascript" src="javascripts/shadedborder_min.js"></script>'."\n";
		echo '<script type="text/javascript" charset="iso-8859-1">'."\n";
		echo "var border = RUZEE.ShadedBorder.create({ corner:8, shadow:30,  border:2 });\n";
		if($script){
				echo $script;
		}
		echo '</script>'."\n";
		echo "<link rel='stylesheet' href='styles/vbcll.css' type = 'text/css' />\n";
		echo "<!--[if lte IE 7]>";
		echo "<link rel='stylesheet' href='styles/vbcll_ie.css' type = 'text/css' />\n";
		echo "<![endif]-->";
		echo "<!--[if IE 6]>";
		echo "<link rel='stylesheet' href='styles/vbcll_ie6.css' type = 'text/css' />\n";
		echo "<![endif]-->";
		echo "<link rel='alternate' type='application/rss+xml' title='RSS VBCLL: infos' href='http://www.vbcll.ch/rss.php' />\n";
		echo "<title>$page_title</title>\n";
		echo "</head>\n";
		echo "<body onload = 'perso();check_communications();$onload'><a name = 'top' id = 'top' ></a>\n";
		echo "<div id = 'message'></div>\n";
		if(stripos($_SERVER['HTTP_USER_AGENT'],"iphone") !== FALSE){
			echo "<div style = 'position: relative; margin: 10px auto; line-height: 60px; background-color: #FFF;width: 900px;height: 120px; font-size: 48px; text-align: center;'>Visitez le site pour iphone : <a href = 'iphone/index.php'>www.vbcll.ch/iphone</a></div>\n";
			if(!isset($_SESSION['from_iphone'])) redirect('http://www.vbcll.ch/iphone/');
		}
		echo '<div class="top"></div>'."\n";
		echo "<div id = 'container'>\n";
		echo "<div id = 'center_box_content'>\n";
		echo "<div id = 'center_box' class ='sb'></div>\n";
		echo "</div>\n";
		echo "<div id = 'title'>\n";
		echo "<h1 class = 'pointer'>&nbsp;</h1>\n";
		echo "</div>\n"; ### end title
		$class = ($admin) ? "class = 'comite'" : "";
		$comite = ($admin) ? "<div id = 'comite'>COMITE</div>" : "";
		echo "<div id = 'subtitle' $class><div id = 'search_form'>$search_form</div></div>\n";
		echo "<div id = 'div_bienvenue'>Bienvenue, <span id = 'bienvenue'>$bienvenue</span>$comite</div>\n";
		echo "<div id = 'nav'>\n";
		$content = navigation($admin);
		echo "<h1>navigation</h1>\n";
		echo "<div id = 'navigation'>$content</div>\n";
		if(!$admin){
			if(bref()){
				echo "<h1>en bref</h1>\n";
				echo "<div id = 'bref'>".(bref())."</div>\n";
			} 
			echo "<h1 style = 'position: relative'>perso<span id = 'logout'></span></h1>\n";
			echo "<div id = 'perso'></div>\n";
			echo "<h1>nos partenaires</h1>\n";
			echo "<div id = 'partenaires'>".(partenaire())."</div>\n";
			if(check_cookie()){
				echo "<h1>les anniversaires</h1>\n";
				echo "<div id = 'anniversaire'>".(anniversaire())."</div>\n";
			} 
		}
		echo "</div>\n"; ### end nav
		echo "<div id = 'body'><a name = 'top'></a>\n";
	}


	function pied(){
		echo "</div>\n"; ##### end body
		echo "<div id = 'foot'>\n";
		echo "&copy; Robin Liechti pour le Volley-Ball Club Lutry-Lavaux (2012).\n";
		echo "</div>\n"; ### end foot
		echo "</div>\n"; ### end container
		echo '<div class="bottom">';
		echo '</div>'."\n";


		echo "<div id='autocomplete_choices_search' class='autocomplete'></div>";
		echo "<script type = 'text/javascript'>new Ajax.Autocompleter('search_term', 'autocomplete_choices_search', 'verif_membre.php',{paramName: 'value', minChars: 3, indicator: 'indicator_membre', afterUpdateElement: preview_membre});</script>\n";
		?>
		<script type="text/javascript">
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
		</script>
		<script type="text/javascript">
		var pageTracker = _gat._getTracker("UA-1812786-2");
		pageTracker._initData();
		pageTracker._trackPageview();
		</script>
		<?php
		echo "</body>\n";
		echo "</html>\n";
	}


	function box($title,$content,$width=180,$smallinfo=""){
		$classTitle = ($smallinfo) ? "box_small_title" : "box_title";
		$classContent = ($smallinfo) ? "box_small_content" : "box_content";
		$small = ($smallinfo) ? "_small" : "";
		echo "<div style = 'width: ".$width."px; margin-bottom: 20px;'>\n";
		echo "<div class = 'box' style = 'width: ".($width-2)."px;'>\n";
		if($title) echo "<div class = '$classTitle'>$title</div>\n";
		echo "<div class = '$classContent'>$content</div>\n";
		echo "</div>\n";
		echo "</div>\n";
	}
	function nl2br2($string) {
		$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
		return $string;
	}

	function leftCol($content){
	        if(func_num_args() > 1){
	                $width = "style = 'width: ";
	                $width .= func_get_arg(1);
	                $width .= "%'";
	        }
	        else $width = "";
	        return "<div class = 'twoCol'>\n<div class = 'leftCol'  $width>$content</div>\n";
	}

	function rightCol($content){
	        if(func_num_args() > 1){
	                $width = "style = 'width: ";
	                $width .= func_get_arg(1);
	                $width .= "%'";
	        }
	        else $width = "";
	        return "<div class = 'rightCol' $width>$content</div>\n</div>\n";
	}

	function empty_line_two_col(){
	        $content = leftCol("");
	        $content .= rightCol("");
	        return $content;
	}

	function prepare_info($texte,$cat = ""){
		if(!$cat) $cat = (!empty($_SESSION['cat'])) ? $_SESSION['cat'] : "infos";
		if(get_magic_quotes_gpc()) $texte = stripslashes($texte);
		$texte = str_replace("<br>","\n",$texte);
		$order   = array("\r\n", "\n", "\r");
		$replace = '<br />';
		$texte = str_replace($order, $replace, $texte);
		$texte = ereg_replace("([^A-Za-z]+)_([^_]*)_([^A-Za-z]+)","\\1<span class = 'italic'>\\2</span>\\3",$texte);
		$texte = ereg_replace("\*([^\*]*)\*","<span class = 'bold'>\\1</span>",$texte);
		$texte = ereg_replace("!!([^!]*)!!","<span class = 'highlight'>\\1</span>",$texte);
		$texte = ereg_replace("cit%([^%]*)%\.([^%]*)?%%","<p class = 'erreur'><span class = 'bold'>\\1 a &eacute;crit : </span><br /><br />\\2</p>",$texte);
		$texte = preg_replace("/''(.*?)'':http:\/\/([^\ ]*)?/"," <a href = 'http://\\2'>\\1</a>",$texte);
		$texte = preg_replace("/&#39;&#39;(.*?)&#39;&#39;:http:\/\/([^\ ]*)?/"," <a href = 'http://\\2'>\\1</a>",$texte);
		$texte = preg_replace("/(<img.*?)>/","<div class = 'container_shadow'><div class='shadow'>\\1/><div class='topleft'></div><div class='topright'></div><div class='bottomleft'></div><div class='bottomright'></div></div><br class = 'clear'/></div>",$texte);
		$texte = ereg_replace("==img:([0-9tmp_]*):(img[0-9]*\.[A-Za-z]*)?==","<div class='shadow'><img src='http://www.vbcll.ch/images/$cat/\\1/\\2' alt = 'image $cat' /><div class='topleft'></div><div class='topright'></div><div class='bottomleft'></div><div class='bottomright'></div></div><br class = 'clear'/>",$texte);
		return valid_chars($texte);
	}

	function describe($table){
		$fields = array();
		$q = "desc $table";
		$r = ExecRequete($q);
		while($s = LigneSuivante($r)){
			$fields[$s->Field] = $s->Type;
		}
		return $fields;
	}

	function message($text){
		echo "<script type = 'text/javascript' charset = 'utf-8'>message(\"$text\");</script>\n";
	}

	function check_admin($commission = ""){
		$id = check_cookie();
		if($id){
			$membre = new membre($id);
			$q = "select id from commissions where nom = 'comite'";
			$r = ExecRequete($q);
			$id_comite = ($s = LigneSuivante($r)) ? $s->id : '';
			if(array_key_exists($id_comite,$membre->commissions)){
				$VBCLLADMIN = (!empty($_COOKIE['VBCLLADMIN'])) ? $_COOKIE["VBCLLADMIN"] : "";
				if($VBCLLADMIN){
					$cookie = explode(':',$VBCLLADMIN);
					if($membre = new membre($cookie[0])){
						if($cookie[1] == ($cookie[0]*strlen($membre->nom)+strlen($membre->prenom)*15698)  ){
							return true;
						}
						else return false;
					}
					else return false;
				}
				else{
					return false;
				}
			}
			elseif($commission){
				if(strpos($commission,",") !== FALSE){
					$commissions = explode(",",$commission);
					$q = "select id from commissions where nom in ('".(implode("','",$commissions))."')";
				}
				else $q = "select id from commissions where nom = '$commission'";
				$r = ExecRequete($q);
				while($s = LigneSuivante($r)){
					$id_commission =  $s->id ;
					if(array_key_exists($id_commission,$membre->commissions)){
						error_log("OK $id_commission");
						$VBCLLADMIN = (!empty($_COOKIE['VBCLLADMIN'])) ? $_COOKIE["VBCLLADMIN"] : "";
						if($VBCLLADMIN){
							$cookie = explode(':',$VBCLLADMIN);
							if($membre = new membre($cookie[0])){
								if($cookie[1] == ($cookie[0]*strlen($membre->nom)+strlen($membre->prenom)*15698)  ){
									return true;
								}
							}
						}
					}
				}
				return false;
			}
			else return false;
		}
		else return false;
	}

	function bref(){
		$return = "";
		$q = "select contenu from brefs where date_creation <= curdate() and date_expiration > curdate() and  valide = 1 order by date_expiration asc";
		$r = ExecRequete($q);
		$i = 0;
		while($s = LigneSuivante($r)){
			if(++$i == 1) $return .=  "<ul class = 'bref'>\n";
			$return .=  "<li>".(prepare_info($s->contenu))."</li>\n";
		}
		if($i) $return .=  "</ul>\n";
		#else $return .=  "<p class = 'center italic fade'>pas de br&egrave;ve</p>\n";
		return $return;
	}

	function anniversaire(){
		$return = "";
		$bissextil = (((date('Y')-2000)%4==0) && (date('m')>2)) ? 1 : 0;
		$q = "select membres.id as id, concat(prenom,' ',membres.nom) as membre, equipes.nom as equipe, ddn from membres left join membre_equipes on membres.id = membre_id left join equipes on equipe_id = equipes.id where (dayofyear(ddn)+$bissextil) >= mod(365 + dayofyear(curdate()),365) and dayofyear(ddn) <= mod(365 + dayofyear(date_add(curdate(), interval 7 day)),365) and site = 1 and valide = 1 and fictif = 0 order by date_format(ddn,'%m%d')";
		$r = ExecRequete($q);
		$anni = array();
		while($s = LigneSuivante($r)){
			$photo = "";
			$ddn_array = explode("-",$s->ddn);
			if($ddn_array[1]."-".$ddn_array[2] == date('m-d')){
			// if(date("m-d",safestrtotime($s->ddn)) == date('m-d')){
				if(file_exists("photos/$s->id.jpeg")){
					$membre = new membre($s->id);
					$photo = "<tr><td colspan = '3'>".$membre->photo()."</td></tr>";
				}
			}
			$anni[$s->id] = "$photo<tr><td onclick = 'show_membre($s->id)' class = 'hover_dark pointer'>".(ucwords(strtolower($s->membre)))."</td><td>".$s->equipe."</td><td class = 'center'>".(format_date($s->ddn,'d.m','anniv'))."</td></tr>";
		}
		if(count($anni)) $return .=  "<table>";
		foreach($anni as $id => $text){
			$return .=  $text;
		}

		if(count($anni)) $return .=  "</table>";
		else $return .=  "<p class = 'center italic fade'>pas d'anniversaire ces prochains jours</p>\n";
		return $return;
	}

	function navigation($admin = 0){
		$return = "";
		$user_id = check_cookie();
		$membre = new membre($user_id);
		if(!$admin || !count($membre->commissions)){
			$navigations = array(
				"accueil" => "index.php",
				"infos" => "infos.php",
				"documents" => "documents.php",
				"inscriptions" => "inscriptions.php",
				"&eacute;quipes" => "equipes.php",
				"membres" => "membre.php",
				"arbitrages" => "arbitrages.php",
				"marquages" => "marquages.php",
				"historique" => "historique.php",
				"beach" => "beach.php",
				"partenaires" => "partenaires.php",
				//"photos" => "photos.php",
				"contacts" => "contacts.php"
			);
			$q = "select id from commissions where nom = 'comite'";
			$r = ExecRequete($q);
			$id_comite = ($s = LigneSuivante($r)) ? $s->id : '';
			if(array_key_exists($id_comite,$membre->commissions)){
				$navigations["<span class = 'non'>comit&eacute;</span>"] = "calendrier_admin.php";
				$comite = 1;
			}
			elseif(count($membre->commissions)){
				$q = "select id,nom from commissions where nom != 'comite'";
				$r = ExecRequete($q);
				while($s = LigneSuivante($r)){
					if($s->nom == 'commission_technique' && array_key_exists($s->id,$membre->commissions)){
						$navigations["<span class = 'non'>gestion</span>"] = "calendrier_admin.php";
					}
					elseif($s->nom == "commission_LN" && array_key_exists($s->id,$membre->commissions)){
						$navigations["<span class = 'non'>gestion</span>"] = "partenaires_admin.php";
					}
					elseif($s->nom == "commission_arb_marq" && array_key_exists($s->id,$membre->commissions)){
						$navigations["<span class = 'non'>gestion</span>"] = "marquages_admin.php";
					}
					elseif($s->nom == 'commission_presse' && array_key_exists($s->id,$membre->commissions)){
						$navigations["<span class = 'non'>gestion</span>"] = "marquages_admin.php";
					}
				}
			}
            else{
				$comite = 0;
			}
			foreach($navigations as $print => $link){
				${"nav_$print"} = array();
			}

			$nav_accueil = array(
				"derni&egrave;res infos" => "#infos",
				"derniers r&eacute;sultats" => "#resultats",
				"prochains matchs" => "#matchs"
			);
			$nav_arbitrages = array(
				"les arbitres" => "arbitrages.php?action=liste",
				"les arbitrages" => "arbitrages.php",
				"devenir arbitre" => "devenir_arbitre.php");

			$nav_marquages = array(
				"les marqueurs" => "marquages.php?action=liste",
				"les marquages" => "marquages.php");
            $commissions = liste("commissions");
			$nav_contacts = array(
				"adresse du club" => "#adresse",
				"les salles" => "#salles");
			$nav_partenaires = array("nos sponsors" => "#sponsors",
						"nos partenaires"=> "#partenaires",
						"nos supporters" => "#supporters");
			foreach($commissions as $id => $nom){
				$commission = new commission($id);
				$nav_contacts[$commission->description] = "#".$nom;
			}
			$nav_contacts["responsables"] = "#responsables";
			$nav_contacts["comptes bancaires"] = "#comptes";
			$nav_contacts["liens"] = "#liens";
			$q = "select * from activites where date >= curdate() and valide = 1";
			$r = ExecRequete($q);
			while($s = LigneSuivante($r)){
				$s->nom = (get_magic_quotes_gpc()) ? stripslashes($s->nom) : $s->nom;
				$nav_inscriptions[$s->nom] = "inscriptions.php?activite=$s->id";
			}

			${"nav_infos"} = array(
				"occupation salles" => "occupation_salles.php"
			);

			$equipes = liste("equipes","nom","num");
			foreach($equipes as $id => $nom){
				${"nav_&eacute;quipes"}[$nom] = "equipes.php?id=$id";
			}
		}
		else{
			$user_id = check_cookie();
			$membre = new membre($user_id);
			$q = "select id from commissions where nom = 'comite'";
			$r = ExecRequete($q);
			$id_comite = ($s = LigneSuivante($r)) ? $s->id : '';
			if(array_key_exists($id_comite,$membre->commissions)){
				$navigations = array(
					"membres" => "membre_admin.php",
					"matchs" => "calendrier_admin.php",
					"infos" => "infos_admin.php",
					"documents" => "documents_admin.php",
					"br&egrave;ves" => "brefs_admin.php",
					"&eacute;quipes" => "equipes_admin.php",
					"arbitrages" => "arbitrages_admin.php",
					"marquages" => "marquages_admin.php",
					"matchs M1" => "matchs_m1_admin.php",
					"salles" => "salles_admin.php",
					"activit&eacute;s" => "activites_admin.php",
					"partenaires" => "partenaires_admin.php",
					"historique" => "historique_admin.php",
					"envoi d'email" => "email_admin.php",
					"comptabilit&eacute;" => "compta_admin.php",
					"<span class = 'oui'>site public</span>" => "index.php"
				);
				$comite = 1;
			}
			elseif(count($membre->commissions)){
				$navigations = array();
				$q = "select id,nom from commissions where nom != 'comite'";
				$r = ExecRequete($q);
				while($s = LigneSuivante($r)){
					if($s->nom == 'commission_technique' && array_key_exists($s->id,$membre->commissions)){
						$navigations += array(
							"membres" => "membre_admin.php",
							"matchs" => "calendrier_admin.php",
							"&eacute;quipes" => "equipes_admin.php",
							"salles" => "salles_admin.php",
							"envoi d'email" => "email_admin.php"
							);
						$comite = 0;
					}
					elseif($s->nom == "commission_LN" && array_key_exists($s->id,$membre->commissions)){
						$navigations += array(
							"matchs" => "calendrier_admin.php",
							"partenaires" => "partenaires_admin.php",
							"matchs M1" => "matchs_m1_admin.php"
						);
						$comite = 0;
					}
					elseif($s->nom == "commission_arb_marq" && array_key_exists($s->id,$membre->commissions)){
						$navigations += array(
							"arbitrages" => "arbitrages_admin.php",
							"marquages" => "marquages_admin.php",
							"envoi d'email" => "email_admin.php"
						);
						$comite = 0;
					}
					elseif($s->nom == "commission_presse" && array_key_exists($s->id,$membre->commissions)){
						$navigations += array(
							"infos" => "infos_admin.php",
							"historique" => "historique_admin.php"
						);
						$comite = 0;
					}

				}
				$navigations += array("<span class = 'oui'>site public</span>" => "index.php");
			}
            else{
				$comite = 0;
				$navigations = array();
			}

		}

		$nav_id = (!isset($_SESSION['navigation'])) ? "accueil" : $_SESSION['navigation'];
		$return .=  "<ul class = 'nav'>\n";
		foreach($navigations as $key => $val){
			$selected = ($key == $nav_id || substr($val,0,-4) == $nav_id) ? "<div class = 'bullet' style = 'position: absolute; left: -20px; width: 7px; height: 14px; background-color: #CC2C30; color: #CC2C30;font-size: 8px'>&nbsp;</div>" : "";
			if($key == 'documents'){
				$q = "select * from documents where valide = 1";
				$r = ExecRequete($q);
				$nouveau = "";
				while($s = LigneSuivante($r)){
					if(!$s->droits || ($s->droits == 'm' && check_cookie()) || ($s->droits == 'c' && check_admin())){
						$document = new document($s->id);
						if($document->date('Ymd') > date('Ymd',mktime(0, 0, 0, date("m")-1, date("d"),   date("Y")))) $nouveau = "<span class = 'non sup bold' style = 'padding-left: 5px'>nouv.</span>";
					}
				}
				$print_key = $key.$nouveau;
			}
			else $print_key = $key;
			if($comite && !$admin){
				if(file_exists(str_replace(".php","",$val)."_admin.php")){
					$return .=  "<li onmouseover = 'document.getElementById(\"edit_".(str_replace(" ","",$key))."\").style.display = \"inline\";' onmouseout = 'document.getElementById(\"edit_".(str_replace(" ","",$key))."\").style.display = \"none\"' style = 'position: relative' >$selected <a href = '$val'>$print_key</a>";
					$return .= "<span id = 'edit_".(str_replace(" ","",$key))."' style = 'position: absolute; right: 0px; display: none;'><a href = '".str_replace(".php","",$val)."_admin.php'><img style = 'padding-left: 5px' src = 'images/icon_edit.png' alt 0 'edit' width = '14' height = '14' /></a></span>";
				}
				else $return .=  "<li style = 'position: relative'>$selected <a href = '$val'>$print_key</a>";
			}
			else $return .=  "<li style = 'position: relative'>$selected <a href = '$val'>$print_key</a>";
			if($key == $nav_id){
				if(isset(${"nav_".$key})){
					if(is_array(${"nav_".$key})){
						$return .=  "<ul class = 'nav sous'>\n";
						foreach(${"nav_".$key} as $subkey => $subval){
							$return .=  "<li class = 'nav sous'>".(lien($subval,$subkey))."</li>\n";
						}
						$return .=  "</ul>\n";
					}
				}
			}
			$return .=  "</li>\n";
		}
		$return .=  "</ul>\n";
		return $return;
	}

	function partenaire(){
		$q = "select distinct(partenaires.id) as id from partenaires inner join types_partenaire on partenaires.type_id = types_partenaire.id inner join soutiens on soutiens.partenaire_id = partenaires.id where soutiens.valide = 'Y' and partenaires.type_id < 4 order by partenaires.type_id, soutiens.prix";
		$r = ExecRequete($q);
		$return = "";
		while($s = LigneSuivante($r)){
			$partenaire = new partenaire($s->id);
			$return .= $partenaire->logo(150);
		}
		$return .= "<br class = 'clear'/>";
		return $return;
	}

	function table_exists($table){
		$q = "show tables";
		$r = ExecRequete($q);
		$found = 0;
		while($s = LigneSuivante($r)){
			if($s->{"Tables_in_".BASE}  == $table) {$found = 1;break;}
		}
		return $found;
	}

	function encode_iso88591($string)
	{
	  $text = '=?utf-8?q?';

	  for( $i = 0 ; $i < strlen($string) ; $i++ )
	  {
	   $val = ord($string[$i]);
	   if($val > 127 or $val == 63)
	   {
	     $val = dechex($val);
	     $text .= '='.$val;
	   }
	   else
	   {
	       $text .= $string[$i];
	   }

	  }
	  $text .= '?=';

	  return $text;
	}

	function mail_marquage($match_no){
		$match = new match($match_no);
		$marqueur1 = new membre($match->marqueur1);
		$email1 = $marqueur1->email;
		if($match->marqueur2){
			$marqueur2 = new membre($match->marqueur2);
			$email2 = $marqueur2->email;
		}
		else $marqueur2 = "";
		$salle = new salle($match->salle);
		$titre = "VBCLL : inscription marquage ".(format_date($match->date));
		$texte = ($marqueur2) ? "[Marqueurs: $marqueur1->prenom $marqueur1->nom et $marqueur2->prenom $marqueur2->nom]\n\n" : "[Marqueur: $marqueur1->prenom $marqueur1->nom]\n\n";
		$texte .= "Bonjour,\n\nCeci est une confirmation de l'inscription pour le marquage du ";
		$texte .= format_date($match->date);
		$texte .= " à ".(format_heure($match->heure))." à la salle : $salle->nom\n\n";
		$texte .= "Le match à marquer est : [No : $match->no] $match->local - $match->visiteur $match->ligue\n\n";
		$texte .= "\n\nMerci de te présenter au plus tard 30 min. avant le début du match.\n\n";
		$texte .= "Salutations sportives,\n\nVBCLL\n\n";
		$texte .= "ps : si tu ne peux pas assurer ce marquage, tu es le seul responsable pour trouver un remplaçant";
		$msg = wordwrap($texte, 70);
		$to = (strpos($email1,"@") !== FALSE) ? $email1."," : "";
		$to .= (strpos($email2,"@") !== FALSE) ? $email2 : "";
		$q = "select nom,prenom,email from membres inner join membre_commissions on membres.id = membre_id where fonction like '%marquage%'";
		$r = ExecRequete($q);
		$email_vbcll = ($s = LigneSuivante($r)) ? $s->email : "vbcll@vbcll.ch";
#		$email_vbcll = "robin.liechti@vtxnet.ch";
		if(!$to){$to = $email_vbcll; $cc = "";}
		else $cc = $email_vbcll;
		$from = $email_vbcll;
		$subject = encode_iso88591($titre);
		$headers =    "MIME-Version: 1.0\r\n" .
		               "Content-type: text/plain; charset=utf-8; format=flowed\r\n" .
		               "Content-Transfer-Encoding: 8bit\r\n" .
						"Cc: $cc\r\n" .
		               "From: $from\r\n" .
		               "X-Mailer: PHP" . phpversion();

		return mail($to, $subject, $msg, $headers);
	}

	function mail_arbitrage($match_no){
		$match = new arbitrage($match_no);
		$arbitre1 = new membre($match->arbitre1);
		$email1 = $arbitre1->email;
		if($match->arbitre2){
			$arbitre2 = new membre($match->arbitre2);
			$email2 = $arbitre2->email;
		}
		else $arbitre2 = "";
		$salle = new salle($match->salle);
		$titre = "VBCLL : inscription arbitrage ".(format_date($match->date));
		$texte = "Bonjour,\n\nCeci est une confirmation de l'inscription pour l'arbitrage du ";
		$texte .= format_date($match->date);
		$texte .= " à ".(format_heure($match->heure))." à la salle : $salle->nom\n\n";
		$texte .= "Le match à arbitrer est : [No : $match->no] $match->local - $match->visiteur $match->ligue\n\n";
		$texte .= ($arbitre2) ? "Les arbitres sont $arbitre1->prenom $arbitre1->nom et $arbitre2->prenom $arbitre2->nom.\n\n" : "";
		$texte .= "\n\nMerci de te présenter au plus tard 30 min. avant le début du match.\n\n";
		$texte .= "Salutations sportives,\n\nVBCLL\n\n";
		$texte .= "ps : si tu ne peux pas assurer cet arbitrage, tu es le seul responsable pour trouver un remplaçant";
		$msg = wordwrap($texte, 70);
		$to = (strpos($email1,"@") !== FALSE) ? $email1.", " : "";
		$to .= (strpos($email2,"@") !== FALSE) ? $email2 : "";
		$q = "select nom,prenom,email from membres inner join membre_commissions on membres.id = membre_id where fonction like '%arbitrage%'";
		$r = ExecRequete($q);
		$email_vbcll = ($s = LigneSuivante($r)) ? $s->email : "vbcll@vbcll.ch";
#		$email_vbcll = "robin.liechti@vtxnet.ch";
		if(!$to){$to = $email_vbcll; $cc = "";}
		else $cc = $email_vbcll;
		$from = $email_vbcll;
		$subject = encode_iso88591($titre);
		$headers =    "MIME-Version: 1.0\r\n" .
		               "Content-type: text/plain; charset=utf-8; format=flowed\r\n" .
		               "Content-Transfer-Encoding: 8bit\r\n" .
						"Cc: $cc\r\n" .
		               "From: $from\r\n" .
		               "X-Mailer: PHP" . phpversion();
		return mail($to, $subject, $msg, $headers);
	}

	function rmdirtree($dirname) {
	    if (is_dir($dirname)) {    //Operate on dirs only
	        $result=array();
	        if (substr($dirname,-1)!='/') {$dirname.='/';}    //Append slash if necessary
	        $handle = opendir($dirname);
	        while (false !== ($file = readdir($handle))) {
	            if ($file!='.' && $file!= '..') {    //Ignore . and ..
	                $path = $dirname.$file;
	                if (is_dir($path)) {    //Recurse if subdir, Delete if file
	                    $result=array_merge($result,rmdirtree($path));
	                }else{
	                    unlink($path);
	                    $result[].=$path;
	                }
	            }
	        }
	        closedir($handle);
	        rmdir($dirname);    //Remove dir
	        $result[].=$dirname;
	        return $result;    //Return array of deleted items
	    }else{
	        return false;    //Return false if attempting to operate on a file
	    }
	}

	function print_email($email){
		if(check_cookie() || check_cookie_email()) return "<a href = 'mailto:$email'>$email</a>";
		else{
			$_SESSION['print_email'] = $email;
			return "<a href = 'javascript:form_email()'>email: cliquez-ici</a>";
		}
	}

	function mailing_list($nom,$email,$status){
		return TRUE;
	}

	function is_ie6(){
		return(strpos($_SERVER['HTTP_USER_AGENT'],"MSIE 6") !== FALSE) ? 1 : 0;
	}

	function vbcll_log($string){
		// $fh = fopen(LOG,"a");
		// $endl = (substr($string,-1,1) == "\n") ? "" : "\n";
		// fwrite($fh,$string.$endl);
		// fclose($fh);
	}

	function get_salles_lutry(){
		$q = "select no from salles where vbcll = 1";
		$r = ExecRequete($q);
		$salles = array();
		while($s = LigneSuivante($r)){
			$salles[] = $s->no;
		}
		return $salles;
	}

	function valid_chars($str){
	    $conv = array();
		$conv[chr(130)] = chr(39); // apostrophe
		$conv[chr(145)] = chr(39); // apostrophe
		$conv[chr(146)] = chr(39); // apostrophe
		$conv[chr(132)] = chr(34); // guillemet
		$conv[chr(139)] = chr(34); // guillemet
		$conv[chr(155)] = chr(34); // guillemet
		$conv[chr(147)] = chr(34); // guillemet
		$conv[chr(148)] = chr(34); // guillemet
		$conv[chr(150)] = chr(45); // tiret
		$conv[chr(151)] = chr(45); // tiret
	    $conv[chr(133)] = chr(46).chr(46).chr(46); // points de suspension
		return str_replace(array_keys($conv),array_values($conv),$str);
	}

	if (!function_exists('str_ireplace'))  {
		function str_ireplace($search,$replace,$subject) {
    		$token = '^[[term^]';
    		$haystack = strtolower($subject);
    		$needle = strtolower($search);
		$c=0;
    		while (($pos=strpos($haystack,$needle))!==FALSE)  {
      			$c++;
      			$subject = substr_replace($subject,$token,$pos,strlen($search));
      			$haystack = substr_replace($haystack,$token,$pos,strlen($search));
    		}
    		while (($pos=strpos($subject,$token))!==FALSE)  {
      			$subject = substr_replace($subject,$replace,$pos,strlen($token));
    		}
    		return $subject;
  		}
	}

	if (!function_exists("stripos")) {
 		 function stripos($str,$needle,$offset=0)
  		{
      			return strpos(strtolower($str),strtolower($needle),$offset);
  		}
	}

	if (!function_exists("array_combine")) {
		function array_combine($arr1,$arr2) {
		   $out = array();
		   foreach($arr1 as $key1 => $value1)    {
		    $out[$value1] = $arr2[$key1];
		   }
		   return $out;
		}
	}


	function array_isearch($str, $array) {
	        foreach($array as $k => $v) {
	            if(strcasecmp($str, $v) == 0) return $k;
	        }
	        return false;
	    }

	function CapitalizeLastName($name) {
	    $name = strtolower($name);
	    $name = join("'", array_map('ucwords', explode("'", $name)));
	    $name = join("-", array_map('ucwords', explode("-", $name)));
	    $name = join("Mac", array_map('ucwords', explode("Mac", $name)));
	    $name = join("Mc", array_map('ucwords', explode("Mc", $name)));
	    return $name;
	}

	function safestrtotime($strInput)
	{
	    $yearSkew = 0;
		$iVal = -1;
	    for ($i=1900; $i<=1969; $i++)
	    {
	        // Check for this year string in date
	        $strYear = (string)$i;
	        if (!(strpos($strInput, $strYear)===false))
	        {
	            $replYear = $strYear;
	            $yearSkew = 1970 - $i;
	            $strInput = str_replace($strYear, '1970', $strInput);
	        }
	    }
	    $iVal = strtotime($strInput);
	    if ($yearSkew> 0)
	    {
	        $numSecs = (60 * 60 * 24 * 365 * $yearSkew);
	        $iVal = $iVal - $numSecs;
	        $numLeapYears = 0;  // determine number of leap years in period
	        for ($j=$replYear; $j<=1969; $j++)
	        {
	            $thisYear = $j;
	            $isLeapYear = false;
	            // Is div by 4?
	            if (($thisYear % 4) == 0)
	            {
	                $isLeapYear = true;
	            }
	            // Is div by 100?
	            if (($thisYear % 100) == 0)
	            {
	                $isLeapYear = false;
	            }
	            // Is div by 1000?
	            if (($thisYear % 1000) == 0)
	            {
	                $isLeapYear = true;
	            }
	            if ($isLeapYear == true)
	            {
	                $numLeapYears++;
	            }
	        }
	        $iVal = $iVal - (60 * 60 * 24 * $numLeapYears);
	    }
	    return $iVal;
	}

	function dateDifference($date1, $date2)
        {
			$diff = abs(strtotime($date2) - strtotime($date1));
			$years = floor($diff / (365*60*60*24));
			$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
			$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
			return array($years,$months,$days);
        }

}
$salles_lutry = get_salles_lutry();
unregister_GLOBALS();

?>
